package com.biostime.qdingding.modules.qd.api;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.JAXBException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alipay.api.AlipayApiException;
import com.biostime.qdingding.common.api.FastResponse;
import com.biostime.qdingding.common.api.ObjResponse;
import com.biostime.qdingding.common.web.BaseController;
import com.biostime.qdingding.modules.qd.api.dto.ContractDto;
import com.biostime.qdingding.modules.qd.entity.Student;
import com.biostime.qdingding.modules.qd.service.AlipayService;
import com.biostime.qdingding.modules.qd.service.ContractService;
import com.biostime.qdingding.modules.qd.service.TransrecordService;
import com.biostime.qdingding.modules.qd.service.WeixinPayService;

/**
 * 支付模块
 * 
 * @author chenweicheng
 * @version 2015-12-30
 */
@RestController
@RequestMapping(value = "${adminPath}/qd/api/pay")
public class PayApi extends BaseController{
	
	public static Logger logger=Logger.getLogger("api"); 
	
	@Autowired
	private WeixinPayService payService;
	
	@Autowired
	private AlipayService alipayService;
	
	@Autowired
	private ContractService contractService;
	
	@Autowired
	private TransrecordService recordService;

	/**
	 * 我的账户/支付合同金额
	 * 微信统一下单
	 * 小马
	 */
	@RequestMapping(value = "payMoney")
	public @ResponseBody String payMoney(HttpServletRequest request) throws Exception {
		String str = null;
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");	
		String money = request.getParameter("money");	
		if (userId != null && !userId.equals("")  && studentId != null && !studentId.equals("") && money !=null 
				&& !money.equals("")) {
			str = payService.payMoney(request);
			System.out.println(str);					
		} 					
		return str;
		
	}
	
	/**
	 * 我的账户/支付合同金额
	 * 微信统一下单
	 * 合生元
	 */
	@RequestMapping(value = "getPrepayId")
	public ObjResponse<String> getPrepayId(HttpServletRequest request) throws Exception {
		String str = null;
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");	
		String money = request.getParameter("money");
		int errCode = 1;
		String message = null;
		PayApi.logger.info("-------------用户Id："+userId+", 学员Id："+studentId+"开始使用微信支付-------------"); 
		
		if (userId != null && !userId.equals("")  && studentId != null && !studentId.equals("") && money != null 
				&& !money.equals("")) {
			
			//获取合同列表
			Student student=new Student();
			student.setId(studentId);
			List<ContractDto> listContract=contractService.apiGetContract(studentId);
			
			double needPay = 0d;
			if(listContract != null && !listContract.isEmpty()){
				double amount = listContract.get(0).getAmount();
				double pay = recordService.apiGetRecharge(studentId,String.valueOf(listContract.get(0).getId()));
				needPay = amount - pay;
			}			
			if(Double.valueOf(money) <= needPay){
				str = payService.payMoney(request);
				errCode = 0;
				message = "获取预付单成功";
				System.out.println(str);
			}else{
				message = "获取预付单失败,支付金额不能大于待付金额";
			}
		}else{
			message = "获取预付单失败,请检查参数";
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj(str);	
		
	}	
		
	/**
	 * 微信支付回调
	 */
	@RequestMapping(value = "payReturn")
	public ObjResponse<String> test(@RequestBody String body) throws IOException, JAXBException {
		int errCode = 1;
		String message = null;
				 
		if(body != null){	
			payService.wexinPayReturn(body);
        	errCode = 0;
			message = "回调成功";					
		}else{
			message = "回调失败,请检查参数";
		}		
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj(body);		 	
	}
	
	/**
	 * 微信确认支付
	 * （已废弃）
	 */
	@RequestMapping(value = "weixinPayConfirm")
	public ObjResponse<String> payConfirm(String userId,String studentId,String out_trade_no) throws IOException, JAXBException {
		int errCode = 1;
		String message = null;						
		return FastResponse.create().errMsg(message).errCode(errCode).obj("支付确认");		 	
	}
	
	/**
	 * 获取支付信息
	 * 支付宝
	 * @throws UnsupportedEncodingException 
	 */	
	@RequestMapping(value = "alipayOrderInfo")
	public ObjResponse<String> alipayGetOrderNo(HttpServletRequest request) throws UnsupportedEncodingException{
		String userId = request.getParameter("userId");
		String studentId = request.getParameter("studentId");
		String price = request.getParameter("price");
		String centerId = request.getParameter("centerId");
		int errCode = 1; 
		String message = null;	
		String payMessage = null;
		PayApi.logger.info("-------------用户Id："+userId+", 学员Id："+studentId+"开始使用支付宝支付-------------"); 
		
		if(userId != null && !userId.equals("") && studentId != null && !studentId.equals("") && price != null && !price.equals("")
				&& centerId != null && !centerId.equals("")){
			payMessage = alipayService.getOrderInfo(request);
			errCode = 0;
			message = "获取支付信息成功";
		}else{
			message = "获取支付信息失败，参数不全";
		}
		
		return FastResponse.create().errMsg(message).errCode(errCode).obj(payMessage);
	}		
		
	/**
	 * 支付宝支付回调
	 */	
	@RequestMapping(value = "alipayPayReturn")
	public String alipayPayReturn(HttpServletRequest request) throws AlipayApiException, NumberFormatException, UnsupportedEncodingException, JAXBException{
		String out_trade_no = request.getParameter("out_trade_no");
		String trade_no = request.getParameter("trade_no");
		String trade_status = request.getParameter("trade_status");
		String total_fee = request.getParameter("total_fee");
		if(alipayService.checkSign(request)){
			alipayService.alipayPayReturn(out_trade_no, trade_no, trade_status,Double.parseDouble(total_fee));  
		}		 
		return "success";
	}	
		
}
